<template>
  <d2-container class="page">
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt />
    </el-dialog>
    <el-dialog
      :title="createOrEdit"
      :visible.sync="dialogFormVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form :model="form" ref="form">
        <el-form-item label="店铺" :label-width="formLabelWidth">
          <el-select v-model="form.shopId" placeholder="请选择">
            <el-option
              v-for="item in options4shopList"
              :key="item.id"
              :label="item.shopName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="教室" :label-width="formLabelWidth">
          <el-select v-model="form.classRoomId" placeholder="请选择">
            <el-option
              v-for="item in options4classroom"
              :key="item.value"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="课程" :label-width="formLabelWidth">
          <el-select v-model="form.courseId" placeholder="请选择" filterable>
            <el-option
              v-for="item in options4course"
              :key="item.value"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="教师" :label-width="formLabelWidth">
          <el-select v-model="form.teacherId" placeholder="请选择" filterable>
            <el-option
              v-for="item in options4teacher"
              :key="item.value"
              :label="item.realName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <!--
        <el-form-item label="开始时间" :label-width="formLabelWidth">
          <el-date-picker
            v-model="form.courseStartTime"
            type="datetime"
            placeholder="选择日期时间"
            value-format=" yyyy-MM-dd HH:mm"
            format="yyyy-MM-dd HH:mm"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" :label-width="formLabelWidth" prop="name">
          <el-date-picker
            v-model="form.courseEndTime"
            type="datetime"
            placeholder="选择日期时间"
            value-format=" yyyy-MM-dd HH:mm"
            format="yyyy-MM-dd HH:mm"
          ></el-date-picker>
        </el-form-item>
        
        <el-form-item label="">
          <el-row :gutter="70">
            <div :key="index" v-for="(item, index) in buttonList">
              <el-col :span="5">
                <el-button
                  style="width:150px"
                  @click="getTableData2(item.code)"
                >{{item.name}}</el-button>
              </el-col>
            </div>
          </el-row>
        </el-form-item>
        -->
        <el-form-item label="日期" :label-width="formLabelWidth">
          <el-date-picker
            v-model="form.startDate"
            type="date"
            placeholder="选择日期"
            value-format="yyyy-MM-dd"
            format="yyyy-MM-dd"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="时间段" :label-width="formLabelWidth">
          <el-select v-model="form.timeinterval" placeholder="请选择">
            <el-option
              v-for="item in buttonList"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleCreateNew('form')">确 定</el-button>
      </div>
    </el-dialog>
    <el-button type="primary" size="mini" @click="showCreateDlg('form')">新建</el-button>&nbsp;
    <el-date-picker
      size="mini"
      v-model="selectedDate"
      type="date"
      placeholder="选择日期"
      value-format="yyyy-MM-dd"
      format="yyyy-MM-dd"
    ></el-date-picker>&nbsp;
    <el-select v-model="shopId" placeholder="请选择" size="mini">
      <el-option
        v-for="item in shopList"
        :key="item.id"
        :label="item.shopName"
        :value="item.id">
      </el-option>
    </el-select>&nbsp;
    <el-button type="primary" size="mini" @click="refresh">搜索</el-button>
    <el-divider></el-divider>
    <el-table
      stripe
      ref="multipleTable"
      :data="tableData"
      tooltip-effect="dark"
      style="width: 100%"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column label="序号" type="index" width="50"></el-table-column>
      <!-- <el-table-column label="id" width="120">
        <template slot-scope="scope">{{ scope.row.id }}</template>
      </el-table-column>-->
      <el-table-column label="店铺">
        <template slot-scope="scope">{{ scope.row.shopName }}</template>
      </el-table-column>
      <el-table-column label="类别">
        <template slot-scope="scope">{{ scope.row.courseTypeName }}</template>
      </el-table-column>
      <!-- <el-table-column label="图片">
        <template slot-scope="scope">
          <img v-bind:src="scope.row.avatarUrl" style="width:30%">
        </template>
      </el-table-column>-->
      <el-table-column label="教室" width="120">
        <template slot-scope="scope">{{ scope.row.classRoomName }}</template>
      </el-table-column>
      <el-table-column label="课程" width="200">
        <template slot-scope="scope">{{ scope.row.courseName }}</template>
      </el-table-column>
      <el-table-column label="教师">
        <template slot-scope="scope">{{ scope.row.teacherName }}</template>
      </el-table-column>
      <el-table-column label="开始时间" width="200">
        <template slot-scope="scope">{{ scope.row.courseStartTime }}</template>
      </el-table-column>
      <el-table-column label="结束时间" width="200">
        <template slot-scope="scope">{{ scope.row.courseEndTime }}</template>
      </el-table-column>
      <el-table-column label="状态" :formatter="statusFormatter" prop="status"></el-table-column>
      <el-table-column label="创建时间" width="200">
        <template slot-scope="scope">{{ scope.row.createTime }}</template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="150" fixed="right">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" @click="showEditDlg(scope.row)" icon="el-icon-edit"></el-button>
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.row)"
            icon="el-icon-delete"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>
    <br />
    <el-pagination
      background
      layout="prev, pager, next"
      :page-size="25"
      :total="$data._total"
      @prev-click="prev_click"
      @next-click="next_click"
      @current-change="current_change"
    ></el-pagination>
  </d2-container>
</template>

<script>
import {
  fetchList,
  createOrEdit,
  queryById,
  deleteById,
  baseDataList
} from "@/api/sys.schedule";

import * as dict from "@/api/sys.dict";
import * as shops from "@/api/sys.shops";

export default {
  components: {},
  data() {
    return {
      shopId: null,
      shopList: null,
      options4shopList: null,
      listQuery: {},
      selectedDate: null,
      _total: 150,
      buttonList: [],
      options4course: [],
      options4classroom: [],
      options4teacher: [],
      options: [{ value: "1", label: "客户" }, { value: "2", label: "私教" }],
      fileList: [],
      tableData: [],
      multipleSelection: [],
      dialogFormVisible: false,
      form: {
        classRoomId: "",
        courseId: "",
        teacherId: "",
        courseStartTime: "",
        courseEndTime: "",
        timeinterval: "",
        startDate: ""
      },
      formLabelWidth: "120px",
      dialogImageUrl: "",
      dialogVisible: false,
      createOrEdit: "",
      downloadPath: ""
    };
  },
  mounted() {
    const formatDate = time => {
      // 格式化日期，获取今天的日期
      const Dates = new Date(time);
      const year = Dates.getFullYear();
      const month =
        Dates.getMonth() + 1 < 10
          ? "0" + (Dates.getMonth() + 1)
          : Dates.getMonth() + 1;
      const day =
        Dates.getDate() < 10 ? "0" + Dates.getDate() : Dates.getDate();
      return year + "-" + month + "-" + day;
    };

    const _date = formatDate(new Date().getTime()); // 当前时间
    this.listQuery.startDate = _date;
    
    this.getList();
    this.$route.meta.title = "排课";

    dict.fetchList("{parentCode: 'time-interval'}").then(resp => {
      this.buttonList = resp.data;
    });

    shops.fetchList(null).then(response => {
      this.shopList = response.records;
    });


  },
  created() {
    // 读数据字典
    baseDataList(1).then(response => {
      if (response.success) this.options4course = response.data;
    });

    baseDataList(2).then(response => {
      if (response.success) this.options4classroom = response.data;
    });

    baseDataList(3).then(response => {
      if (response.success) this.options4teacher = response.data;
    });

    baseDataList(4).then(response => {
      this.options4shopList = response;
    });
  },
  methods: {
    prev_click(e) {
      console.log(e);
    },
    next_click(e) {
      console.log(e);
    },
    current_change(e) {
      console.log(e);
    },
    statusFormatter(row, column) {
      let status = row.status;
      if (status < 3) {
        return "未开课";
      } else {
        return "已开课";
      }
    },

    refresh() {
      this.listQuery.startDate = this.selectedDate;
      this.listQuery.shopId = this.shopId;

      this.getList();
    },

    showCreateDlg(formName) {
      this.dialogFormVisible = true;
      this.createOrEdit = "新建";

      // if (this.$refs[formName] !== undefined)
      //   this.$refs[formName].resetFields();

      // this.form.classRoomId = "";
      // this.form.courseId = "";
      // this.form.teacherId = "";
      // this.form.courseStartTime = "";
      // this.form.courseEndTime = "";
    },

    showEditDlg(row) {
      this.dialogFormVisible = true;
      this.createOrEdit = "编辑";

      this.form = row;
      let date_time = this.form.courseStartTime.split(" ");
      this.form.startDate = date_time[0];

      this.buttonList.forEach(element => {
        if (element.code.startsWith(date_time[1].substr(0, 5))) {
          this.form.timeinterval = element.code;

          let trim = element.code.replace(/\s+/g, "");
          let tmp = trim.split(";");
          this.form.courseStartTime =
            this.form.startDate + " " + tmp[0] + ":00";
          this.form.courseEndTime = this.form.startDate + " " + tmp[1] + ":00";
        }
      });
    },

    handleUploadSuccess(response, file, fileList) {
      console.log(response);
      if (response.success) this.downloadPath = response.downloadPath;
    },

    handleCreateNew(formName) {
      let that = this;

      const set = that.$refs;
      set[formName].validate(valid => {
        if (valid) {
          let trim = that.form.timeinterval.replace(/\s+/g, "");
          let tmp = trim.split(";");
          that.form.courseStartTime = that.form.startDate + " " + tmp[0] + ":00";
          that.form.courseEndTime = that.form.startDate + " " + tmp[1] + ":00";

          if(that.form.teacherId == null || that.form.teacherId == "") {
            that.$notify({
              title: "提示",
              message: "请选择上课老师",
              type: "error",
              duration: 2000
            });

            return
          }

          createOrEdit(that.form).then(resp => {
            if (resp.success) {
              // that.dialogFormVisible = false;
              that.getList();
              that.$notify({
                title: "提示",
                message: "操作成功",
                type: "success",
                duration: 2000
              });
            } else {
              that.$notify({
                title: "提示",
                message: resp.errorMsg,
                type: "error",
                duration: 2000
              });
            }
          });
        } else {
          return false;
        }
      });
    },

    getList() {
      fetchList(this.listQuery).then(response => {
        if (response.success) this.tableData = response.data;
      });
    },

    handleRemove(file, fileList) {
      console.log(file, fileList);
    },

    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },

    handleDelete(row) {
      this.$confirm("确认删除么?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        deleteById(row.id)
          .then(() => {
            this.getList();
            this.$notify({
              title: "成功",
              message: "删除成功",
              type: "success",
              duration: 2000
            });
          })
          .catch(() => {
            this.$notify({
              title: "失败",
              message: "删除失败",
              type: "error",
              duration: 2000
            });
          });
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.page {
  .logo {
    width: 120px;
  }
  .btn-group {
    color: $color-text-placehoder;
    font-size: 12px;
    line-height: 12px;
    margin-top: 0px;
    margin-bottom: 20px;
    .btn-group__btn {
      color: $color-text-sub;
      &:hover {
        color: $color-text-main;
      }
      &.btn-group__btn--link {
        color: $color-primary;
      }
    }
  }
}
</style>
